const router = require('express').Router();
const getConfig = require('../../utils/configUtil').getConfig;
const crypto = require('crypto');


/**
 * @apiDefine OSS  oss获取签名的
 */

/**
 * @api {get} /osstoken  获取oss的签名等信息
 * @apiVersion 1.0.0
 * @apiName OssTokenGet
 * @apiGroup  OSS
 *
 * @apiDescription 获取oss的host，签名，和id等信息
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/osstoken
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 * @apiSuccess {Object[]} data    返回值数据
 * @apiSuccess {String} data.sign  签名
 * @apiSuccess {String} data.host  域名
 * @apiSuccess {String} data.accessKeyId  accessKeyId
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
     {
        "code": 200,
        "message": "请求成功",
        "data": {
            "sign": "5ushpBPjC97G9/2HunrMH2CRhj0=",
            "host": "xiaoqingjing.oss-cn-beijing.aliyuncs.com",
            "accessKeyId": "LTAI08SBNqF6OJqX"
        }
    }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.get('/', (req, res, next) => {
  const {
    accessKeyId,
    accessKeySecret,
    bucket,
    endPoint
  } = getConfig.oss;
  const host = `${bucket}.${endPoint}.aliyuncs.com`;
  const obj = {
    // 缓存两小时
    expiration: new Date(new Date().getTime() + 1000 * 60 * 60 * 2).toISOString(), // 转换成iso8601的时间格式(官方要求)
    conditions: [
      ['content-length-range', 0, 1048576000000],
    ]
  };
  const policy = Buffer.from(JSON.stringify(obj)).toString('base64');
  const sign = crypto.createHmac('sha1', accessKeySecret).update(policy).digest("base64");
  res.success({
    sign,
    host,
    accessKeyId,
    policy
  })
});

module.exports = router;